package com.changgou.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESMangerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESMangerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@Service
public class ESMangerServiceImpl implements ESMangerService {

    @Autowired
    private ElasticsearchTemplate template;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ESMangerMapper mapper;


    @Override
    public void creadMapperAndIndex() {

        // 创建索引
        template.createIndex(SkuInfo.class);
        // 创建映射
        template.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {

        List<Sku> list = skuFeign.findSkuListBySpuId("all");
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("没有数据查询到，无法导入ES");
        }
        // 将skuList转换为JSON
        String s = JSON.toJSONString(list);


        // 将JSON转换为skuInfo
        // skuInfo是ES的封装实体类
        List<SkuInfo> skuInfos = JSON.parseArray(s, SkuInfo.class);


        for (SkuInfo skuInfo : skuInfos) {
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }

        // 导入ES
        mapper.saveAll(skuInfos);


    }



    @Override
    public void deleteDataBySpuId(String id) {
        List<Sku> skuList = skuFeign.findSkuListBySpuId(id);

        if (CollectionUtils.isEmpty(skuList)) {
            throw new RuntimeException("没有数据查询到，无法从ES中删除数据");
        }

        for (Sku sku : skuList) {
            String skuId = sku.getId();
            mapper.deleteById(Long.parseLong(skuId));
        }



    }

    @Override
    public void importDataBySpuId(String id) {
        List<Sku> skuList = skuFeign.findSkuListBySpuId(id);

        if (CollectionUtils.isEmpty(skuList)) {
            throw new RuntimeException("没有数据查询到，无法导入ES");
        }

        String s = JSON.toJSONString(skuList);

        List<SkuInfo> skuInfos = JSON.parseArray(s, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);

            skuInfo.setSpecMap(map);
        }

        mapper.saveAll(skuInfos);

    }
}
